package controllers;

import models.entities.PaginatedList;
import models.entities.UserEntity;
import models.entities.UserInformation;
import models.exceptions.DeleteEntityException;
import models.exceptions.GetEntityException;
import models.exceptions.UpdateEntityException;
import models.repository.UserRepositorySQL;
import models.repository.common.UserRepository;
import play.data.validation.MinSize;
import play.data.validation.Required;
import play.data.validation.Validation;
import play.mvc.Controller;
import play.mvc.With;

import java.io.IOException;

@With(Secure.class)
public class User extends Controller {
    private static UserRepository repository = new UserRepositorySQL();

    public static void profile() {
        render();
    }

    public static void info() {
        render();
    }

    public static void changePasswordForm() {
        render("User/changePassword.html");
    }

    public static void changePassword(@Required String oldPassword, @Required @MinSize(3) String newPassword) throws UpdateEntityException, IOException {
        if (Validation.hasErrors()) {

        }
        boolean isSuccess = repository.changePassword(oldPassword, newPassword, session.get("username"));
        render(isSuccess);

    }

    @Check("admin")
    public static void list(int pageNumber, int pageSize) throws GetEntityException, IOException {
        PaginatedList<UserEntity> userList = repository.getUserList(pageNumber, pageSize);
        render(userList);
    }

    @Check("admin")
    public static void deleteConfirmation(int id) {
        render(id);
    }

    @Check("admin")
    public static void delete(int id) throws DeleteEntityException, IOException {
        repository.delete(id);
        redirect("/user/list");
    }

    @Check("admin")
    public static void display(int id) throws GetEntityException, IOException {
        UserInformation info = repository.getUserInfo(id);
        render(info);
    }

    @Check("admin")
    public static void editForm(int id) throws GetEntityException, IOException {
        UserEntity user = repository.getUser(id);
        render(user);
    }

    @Check("admin")
    public static void edit(UserEntity user) throws GetEntityException, IOException {
        repository.edit(user);
        list(1, 0);
    }

    @Check("admin")
    public static void setIsAdmin(int id, boolean isAdmin) throws GetEntityException, UpdateEntityException, IOException {
        repository.setIsAdmin(id, isAdmin);
        editForm(id);
    }
}
